package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.ProgressNodeMessage;
import com.ruoyi.system.domain.Quotation;
import com.ruoyi.system.domain.SalesOrder;
import com.ruoyi.system.mapper.QuotationMapper;
import com.ruoyi.system.mapper.SalesOrderMapper;
import com.ruoyi.system.mapper.ProgressNodeMessageMapper;
import com.ruoyi.system.mapper.CustomerMapper;
import com.ruoyi.system.service.IApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApprovalServiceImpl implements IApprovalService {

    @Autowired
    private SalesOrderMapper salesOrderMapper;

    @Autowired
    private QuotationMapper quotationMapper;

    @Autowired
    private ProgressNodeMessageMapper nodeMessageMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    @Transactional
    public int approve(String orderNumber, String approvalResult, String approvalNote) {
        // 1. 根据编号前缀判断订单类型
        if (orderNumber.startsWith("XS")) {
            // 查询销售单
            SalesOrder salesOrder = salesOrderMapper.selectSalesOrderByNumber(orderNumber);
            if (salesOrder == null) {
                throw new ServiceException("销售单不存在");
            }
            return approveSalesOrder(salesOrder, approvalResult, approvalNote);
        }
        else if (orderNumber.startsWith("BJ")) {
            // 查询报价单
            Quotation quotation = quotationMapper.selectQuotationByNumber(orderNumber);
            if (quotation == null) {
                throw new ServiceException("报价单不存在");
            }
            return approveQuotation(quotation, approvalResult, approvalNote);
        }

        throw new ServiceException("无效的订单编号格式");
    }

    @Override
    public TableDataInfo selectPendingApprovals() {
        List<Map<String, Object>> pendingList = new ArrayList<>();

        // 1. 获取待审批的销售单
        List<SalesOrder> salesOrders = salesOrderMapper.selectPendingSalesOrders();
        for (SalesOrder order : salesOrders) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", order.getSalesOrderId());
            map.put("number", order.getNumber());
            map.put("customerName", order.getCustomerName());
            map.put("type", "销售单");
            map.put("createTime", order.getOrderDate());
            pendingList.add(map);
        }

        // 2. 获取待审批的报价单
        List<Quotation> quotations = quotationMapper.selectPendingQuotations();
        for (Quotation quote : quotations) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", quote.getQuotationId());
            map.put("number", quote.getNumber());
            map.put("customerName", quote.getCustomerName());
            map.put("type", "报价单");
            map.put("createTime", quote.getQuotationDate());
            pendingList.add(map);
        }

        // 3. 按创建时间排序
        pendingList.sort((a, b) -> ((Date)b.get("createTime")).compareTo((Date)a.get("createTime")));

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(pendingList);
        rspData.setTotal(pendingList.size());

        return rspData;
    }

    private int approveSalesOrder(SalesOrder salesOrder, String approvalResult, String approvalNote) {
        // 更新销售单状态
        SalesOrder updateOrder = new SalesOrder();
        updateOrder.setSalesOrderId(salesOrder.getSalesOrderId());
        updateOrder.setStatus("已审批".equals(approvalResult) ? "已审批" : "已驳回");

        // 记录审批意见
        ProgressNodeMessage message = new ProgressNodeMessage();
        message.setNodeId(salesOrder.getNodeId());
        message.setMessage(approvalNote);
        nodeMessageMapper.insertNodeMessage(message);

        int rows = salesOrderMapper.updateSalesOrder(updateOrder);

        // 如果审批通过，更新客户合同金额
        if ("已审批".equals(approvalResult)) {
            customerMapper.updateContractAmount(salesOrder.getCustomerId(), salesOrder.getTotalAmount());
        }

        return rows;
    }

    private int approveQuotation(Quotation quotation, String approvalResult, String approvalNote) {
        // 更新报价单状态
        Quotation updateQuotation = new Quotation();
        updateQuotation.setQuotationId(quotation.getQuotationId());
        updateQuotation.setStatus("已审批".equals(approvalResult) ? "已审批" : "已驳回");

        // 记录审批意见
        ProgressNodeMessage message = new ProgressNodeMessage();
        message.setNodeId(quotation.getNodeId());
        message.setMessage(approvalNote);
        nodeMessageMapper.insertNodeMessage(message);

        return quotationMapper.updateQuotation(updateQuotation);
    }
}
